<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '编辑'" :close-on-click-modal="false"
	           :close-on-press-escape="false">
		<el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmitHandle()"
		         label-width="120px">
			<el-form-item prop="name" label="名称">
				<el-input v-model="dataForm.name" placeholder="名称"></el-input>
			</el-form-item>
			<el-form-item prop="parentName" label="上级部门" class="dept-list">
				<el-popover v-model:visible="deptListVisible" ref="deptListPopoverRef" placement="bottom-start"
				            trigger="click">
					<el-tree
						:data="deptList"
						:props="{ label: 'name', children: 'children' }"
						node-key="id"
						ref="deptListTreeRef"
						:highlight-current="true"
						:expand-on-click-node="false"
						accordion
						@current-change="deptListTreeCurrentChangeHandle">
					</el-tree>
					<template #reference>
						<el-input v-model="dataForm.parentName" :readonly="true" placeholder="上级部门">
							<template #suffix>
								<i
									v-if="superAdmin === 1 && dataForm.pid !== '0'"
									@click.stop="deptListTreeSetDefaultHandle()"
									class="el-icon-circle-close el-input__icon">
								</i>
							</template>
						</el-input>
					</template>
				</el-popover>

			</el-form-item>
			<el-form-item prop="sort" label="排序">
				<el-input-number v-model="dataForm.sort" controls-position="right" :min="0"
				                 label="排序"></el-input-number>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import debounce from 'lodash/debounce'
import {computed, nextTick, reactive, ref, unref} from "vue";

import {useStore} from "vuex";
import http from "../../../utils/request.js";
import {message} from "../../../utils/commonScript.js";

const emit = defineEmits(['refreshDataList'])
const store = useStore()
const visible = ref(false)
const deptList = ref([])
const deptListVisible = ref(false)
const dataForm = reactive({
	id: '',
	name: '',
	pid: '',
	parentName: '',
	sort: 0
})
const dataFormRef = ref()
const deptListTreeRef = ref()
const deptListPopoverRef = ref()
const dataRule = computed(() => {
	return {
		name: [
			{required: true, message: '必填项不能为空', trigger: 'blur'}
		],
		parentName: [
			{required: true, message: '必填项不能为空', trigger: 'change'}
		]
	}
})
const superAdmin = computed(() => {
	return store.state.user.superAdmin
})
const init = (id = '') => {
	visible.value = true
	dataForm.id = id
	nextTick(() => {
		dataFormRef.value.resetFields()
		getDeptList().then(() => {
			if (dataForm.id) {
				getInfo()
			} else if (superAdmin.value === 1) {
				deptListTreeSetDefaultHandle()
			}
		})
	})
}
// 获取部门列表
const getDeptList = () => {
	return http.get('/sys/dept/list').then(({data: res}) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}
		deptList.value = res.data
	}).catch(() => {
	})
}
// 获取信息
const getInfo = () => {
	http.get(`/sys/dept/${dataForm.id}`).then(({data: res}) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}

		dataForm.name = res.data.name
		dataForm.pid = res.data.pid
		dataForm.parentName = res.data.parentName
		dataForm.sort = res.data.sort
		if (dataForm.pid === '0') {
			return deptListTreeSetDefaultHandle()
		}
		deptListTreeRef.value.setCurrentKey(dataForm.pid)
	}).catch(() => {
	})
}
// 上级部门树, 设置默认值
const deptListTreeSetDefaultHandle = () => {
	dataForm.pid = '0'
	dataForm.parentName = '一级部门'
}
// 上级部门树, 选中
const deptListTreeCurrentChangeHandle = (data) => {
	dataForm.pid = data.id
	dataForm.parentName = data.name
	deptListVisible.value = false
}
// 表单提交
const dataFormSubmitHandle = debounce(function () {
	dataFormRef.value.validate((valid) => {
		if (!valid) {
			return false
		}
		http[!dataForm.id ? 'post' : 'put']('/sys/dept', dataForm).then(({data: res}) => {
			if (res.code !== 0) {
				return message.error(res.msg)
			}
			message({
				message: '操作成功',
				type: 'success',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		}).catch(() => {
		})
	})
}, 1000, {'leading': true, 'trailing': false})

defineExpose({
	init
})
</script>

<style lang="scss">
.mod-sys__dept {
	.dept-list {
		.el-input__inner,
		.el-input__suffix {
			cursor: pointer;
		}
	}
}
</style>
